var ws;
var address = "ws://localhost:2222/example/ssh";
//var address = "ws://10.0.1.3:2222/example/ssh";
var cmd;
myservers = function(){
    var current = {}, availableServers=[], servers=[];
    if(localStorage.servers){
        servers = $.evalJSON(localStorage.servers)
    }

    init_servers = function(){
        $.each(servers, function(index, server){
            availableServers.push({"label":server.ip, "value": server.ip, "name":server.name, "password":server.password})
        })
    }

    clean = function(){
        $("#name").val("")
        $("#password").val("")
    }

    existed = function(ip){
        if(!ip) return false
        exist = false
        $.each(servers, function(index, server){
            if(ip == server.ip){
                exist = true
            }
        })
        return exist
    }

    register = function(ip, name, pwd, width, height){
        if(ip){
            if(!existed(ip)){
                servers.push({
                    "ip":ip,
                    "name":name,
                    "password":pwd
                })

                localStorage.servers =$.toJSON(servers)
            }
            current.ip = ip
            current.name = name
            current.pwd = pwd 
        }
    }

    init_servers()
    return {
        "reg": register, 
        "current":current,
        "availableServers":availableServers
        }
}()


$(function () {
    startbtn();

    $("#ip").autocomplete({
        source: myservers.availableServers,
        appendTo: "header",
        delay:"100",
        autoFocus: true,
        open: function(event, ui){
            $.each($(".ui-autocomplete .ui-corner-all"), function(index, item){
                /*
                $new_item = $(item).width("60%")
                del_btn = $("<span>del</span>").css("float","right").width("30%").css("backgroundColor", "yellow")
                $new_item.after(del_btn)
                */
            })
        },
        focus: function(event, ui){
            //console.info(event)
            //console.info(ui)
        },
        select: function(event, ui) {
            server = ui.item
            $("#name").val(server.name)
            $("#password").val(server.password)
        }
    });
})

function clearbtn() {
    $("input[name='clear']").click(function () {
        $("textarea[name='msg']").val("");
    })
}


function exeResult(data) {
    if(data.result == "CLEAR"){
        $("#main_shower").html("")
    }

}
function showResult(data) {
    result = data.result
    /*
    font_len = result.replace(/[^\x00-\xff]/g,"**").length * 12
    max_len = $("#main_shower").width()

    if(font_len > max_len){
        font_len = font_len - max_len
    }
    */
    $("#main_shower").append(result)
    $(".cmd_input").remove()
    $sender = $("<input class='cmd_input' autofocus>").keydown(function(arg){
        exec_cmd = $(this).val() || ""
        console.info($("#cmd_input").val())
        
        switch(arg.keyCode){
            case 9:
                ws.send($.toJSON({"keycode":"TAB", "_mapping": "keycode", "command": exec_cmd}))
                event.returnValue=false;
                break
            case 13:
                ws.send($.toJSON({"command":exec_cmd}));
                break
        }
    })
    $("#main_shower").append($sender)
    $(":input[name='command']").val("")

    var obj = $("#main_shower")[0]
    obj.scrollTop= obj.scrollHeight;
}
function showtty(data){
    if(data.status == "FAIL"){
        alert(data.message)
        window.location.reload()
    }else{
        $("header input").attr("disabled","disabled") 
    }
}


function startbtn() {
    $("input[name='startBtn']").click(function () {
        var name = $("#name").val();
        var pwd = $("#password").val();
        var ip = $("#ip").val();
        addr = address + "?name=" + name +"&ip="+ ip+"&password="+pwd;
        open = function () {
            if (typeof(Storage)!=="undefined"){
                myservers.reg(ip, name, pwd)
            }
        }
        close = function () {
            alert("服务器已断开连接");
            location.reload();
        };


        ws = new openWebsocket(addr, open, close);
    })
}

function logout() {
    ws.send($.toJSON({"_mapping":"logout"}));
}
